package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.score.ScoreAddRequest;
import com.SmartCampus.system.model.dto.score.ScoreQueryRequest;
import com.SmartCampus.system.model.dto.score.ScoreUpdateRequest;
import com.SmartCampus.system.model.entity.Score;
import com.SmartCampus.system.model.entity.Subjectcategory;
import com.SmartCampus.system.model.entity.User;
import com.SmartCampus.system.model.vo.ScoreVO;
import com.SmartCampus.system.service.ScoreService;
import com.SmartCampus.system.service.SubjectcategoryService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 成绩接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/score")
@Slf4j
@Api(tags = "成绩接口")
public class ScoreController {

    @Resource
    private ScoreService scoreService;

    @Resource
    private UserService userService;

    @Resource
    private SubjectcategoryService subjectcategoryService;

    // region 增删改查

    /**
     * 创建成绩
     *
     * @param scoreAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建成绩")
    public BaseResponse<Long> addScore(@RequestBody ScoreAddRequest scoreAddRequest, HttpServletRequest request) {
        if (scoreAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Score score = new Score();
        QueryWrapper<User> queryUser = new QueryWrapper<>();
        QueryWrapper<Subjectcategory> querySubjectcategory = new QueryWrapper<>();
        queryUser.eq("username", scoreAddRequest.getStudentName());
        querySubjectcategory.eq("subjectName", scoreAddRequest.getCourseName());
        Subjectcategory subjectcategory = subjectcategoryService.getOne(querySubjectcategory);
        if (subjectcategory == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "课程不存在");
        }
        if (userService.count(queryUser) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学生不存在");
        }
        User user = userService.getOne(queryUser);
        BeanUtils.copyProperties(scoreAddRequest, score);
        score.setStudentId(user.getId());
        score.setCourseId(subjectcategory.getSubjectId());
        boolean result = scoreService.save(score);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(score.getId());
    }

    /**
     * 删除成绩
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除成绩")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = scoreService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新成绩（仅管理员）
     *
     * @param scoreUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新成绩（仅管理员）")
    public BaseResponse<Boolean> updateUser(@RequestBody ScoreUpdateRequest scoreUpdateRequest) {
        if (scoreUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        QueryWrapper<Score> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", scoreUpdateRequest.getId());
        Score score = scoreService.getOne(queryWrapper);
        if (scoreUpdateRequest.getScore() == null || scoreUpdateRequest.getScore().equals("")) {
            scoreUpdateRequest.setScore(score.getScore());
        }
        if (scoreUpdateRequest.getRemarks() == null || scoreUpdateRequest.getRemarks().equals("")) {
            scoreUpdateRequest.setRemarks(score.getRemarks());
        }

        BeanUtils.copyProperties(scoreUpdateRequest, score);
        boolean result = scoreService.updateById(score);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取全部成绩列表（仅管理员）
     *
     * @param scoreQueryRequest
     * @return
     */
    @PostMapping("/get/page")
    @ApiOperation(value = "分页获取全部成绩列表（仅管理员）")
    public BaseResponse<Page<ScoreVO>> getScoreByAll(@RequestBody ScoreQueryRequest scoreQueryRequest) {
        long current = scoreQueryRequest.getCurrent() == 0 ? 1 : scoreQueryRequest.getCurrent();
        long size = scoreQueryRequest.getPageSize() == 0 ? 10 : scoreQueryRequest.getPageSize();
        Page<ScoreVO> page = new Page<>(current, size);
        Page<ScoreVO> scorePage = scoreService.getScoreByAll(page, scoreQueryRequest);
        if (scorePage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(scorePage);
    }

    /**
     * 分页获取用户的全部成绩列表
     *
     * @param scoreQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/my")
    @ApiOperation(value = "分页获取用户的全部成绩列表")
    public BaseResponse<Page<ScoreVO>> getScoreByMy(@RequestBody ScoreQueryRequest scoreQueryRequest, HttpServletRequest request) {
        if (scoreQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userService.getLoginUser(request).getId();
        long current = scoreQueryRequest.getCurrent() == 0 ? 1 : scoreQueryRequest.getCurrent();
        long size = scoreQueryRequest.getPageSize() == 0 ? 10 : scoreQueryRequest.getPageSize();

        Page<ScoreVO> page = new Page<>(current, size);
        Page<ScoreVO> scorePage = scoreService.getScoreByMy(page, scoreQueryRequest, userId);
        if (scorePage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(scorePage);
    }
    // endregion
}
